<?php

namespace app\api\controller\mycurrency;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\billiard\StoreGoods;
use app\common\model\mycurrency\LeaseOrder;
use app\common\model\mycurrency\LeaseOrderDevice;
use app\common\model\mycurrency\LeaseOrderPay;
use app\common\model\mycurrency\LeaseStrategy;
use app\common\model\mycurrency\Pay;
use app\common\model\mycurrency\UserFeedback;
use app\common\model\mycurrency\UserFeedbackType;
use app\common\model\mycurrency\UserMoneyLog;
use app\common\model\mycurrency\UserRechargeOrder;
use app\common\model\mycurrency\UserRechargePackage;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Log;
use think\Validate;

/**
 * 支付接口
 */
class Payment extends Api
{
    protected $noNeedLogin = ['wechatAndAlipayNotify','wechatRefundNotify'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 获得支付参数
    */
    public function getPayCode(){

        $param = $this->request->param();
        $allowOrderType = [
            Pay::ORDER_TYPE_YUE,//用户余额充值订单
            Pay::ORDER_TYPE_YAJIN,//租赁订单押金支付
            Pay::ORDER_TYPE_ZULINFEIYONG,//租赁订单租赁费用支付
        ];
        $allowOrderType = join(',', $allowOrderType);
        $rule = [
            ['order_id', 'require|>:0', '请填写订单id|订单id必须是大于0的数字'],
            ['order_type', "require|in:{$allowOrderType}", '请填写订单类型|无效的订单类型'],
            ['pay_type', 'require|in:wechat,alipay', '请填写支付类型|无效的支付类型']
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        Db::startTrans();
        try {
            $payment_amount = 0;//支付金额
            $pay_type = $param['pay_type'] == 'wechat' ? Pay::PAY_TYPE_WECHAT : Pay::PAY_TYPE_ALIPAY;//支付方式
            $title = '';
            //用户余额充值订单
            if($param['order_type'] == Pay::ORDER_TYPE_YUE){
                $recharge_order = UserRechargeOrder::where(['user_id' => $this->auth->id,'id' => $param['order_id'],'deletetime' => null])->find();
                if(!$recharge_order){
                    throw new Exception('暂无相关余额充值订单信息');
                }
                if($recharge_order['status'] != UserRechargeOrder::STATUS_WEIZHIFU){
                    throw new Exception('订单非待支付状态');
                }
                $payment_amount = $recharge_order['payment_fee'];
                $title = '用户余额充值';
            }
            //租赁订单押金支付
            else if($param['order_type'] == Pay::ORDER_TYPE_YAJIN){
                $lease_deposit = \app\common\model\mycurrency\LeaseDeposit::where(['user_id' => $this->auth->id,'id' => $param['order_id'],'deletetime' => null])->find();
                if(!$lease_deposit){
                    throw new Exception('暂无相关余额充值订单信息');
                }
                if($lease_deposit['status'] != \app\common\model\mycurrency\LeaseDeposit::STATUS_WEIZHIFU){
                    throw new Exception('订单非待支付押金状态');
                }
                $payment_amount = $lease_deposit['amount'];
                $title = '租赁订单押金支付';
            }
            //租赁订单租赁费用支付
            else if($param['order_type'] == Pay::ORDER_TYPE_ZULINFEIYONG){
                $lease_order_pay = LeaseOrderPay::where(['user_id' => $this->auth->id,'id' => $param['order_id'],'deletetime' => null])->find();
                if(!$lease_order_pay){
                    throw new Exception('暂无相关租赁费用支付订单信息');
                }
                if($lease_order_pay['pay_status'] != LeaseOrderPay::PAY_STATUS__DAIZHIFU){
                    throw new Exception('订单非待支付押金状态');
                }
                $payment_amount = $lease_order_pay['money'];
                $title = '租赁订单租赁费用支付';
            }
            $payData = [
                'user_id' => $this->auth->id,
                'ordersn' => Pay::createPayOrderSn(),
                'payment_amount' => $payment_amount,
                'pay_type' => $pay_type,
                'order_type' => $param['order_type'],
                'status' => Pay::STATUS_DAIZHIFU,
                'placeanorder_time' => time(),
                'createtime' => time(),
            ];
            //用户余额充值订单
            if($param['order_type'] == Pay::ORDER_TYPE_YUE){
                $payData['recharge_order_id'] = $param['order_id'];
            }
            //租赁订单押金支付
            else if($param['order_type'] == Pay::ORDER_TYPE_YAJIN){
                $payData['lease_deposit_id'] = $param['order_id'];
            }
            //租赁订单租赁费用支付
            else if($param['order_type'] == Pay::ORDER_TYPE_ZULINFEIYONG){
                $payData['lease_order_pay_id'] = $param['order_id'];
            }
            $payInfo = Pay::create($payData);
            if (!$payInfo->id) {
                throw new Exception('创建支付订单失败，请重试~');
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        //生成支付代码
        $method = 'miniapp';
        $userInfo = \app\common\model\User::get(['id' => $this->auth->id]);
        if ($param['pay_type'] == 'wechat') {
            $openid = $userInfo->wechat_open_id;
        } else {
            $openid = $userInfo->alipay_open_id;
        }
        //回调链接
        $notifyurl = $this->request->domain() . '/api/mycurrency/payment/wechatAndAlipayNotify/paytype/' . $param['pay_type'];
        $returnurl = $this->request->domain() . '/api/mycurrency/payment/wechatAndAlipayNotify/paytype/' . $param['pay_type'] . '/out_trade_no/' . $payInfo->ordersn;
        $response = Service::submitOrder($payInfo->payment_amount, $payInfo->ordersn, $param['pay_type'], $title, $notifyurl, $returnurl, $method, $openid);
        if ($param['pay_type'] == 'wechat') {
            $returnData = ['wechat_pay_code' => $response];
        } else {
            $returnData = ['alipay_pay_code' => $response];
        }
        $this->success('获取支付代码成功', $returnData);
    }

    /**
     * 微信/支付宝支付回调
     */
    public function wechatAndAlipayNotify()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }
        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        Db::startTrans();
        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $outTradeNo = $data['out_trade_no'];
            $payInfo = Pay::where(['ordersn' => $outTradeNo])->lock(true)->find();
            if (!$payInfo) {
                throw new Exception('暂无相关支付信息');
            }
            if($payInfo->status!=Pay::STATUS_DAIZHIFU){
                throw new Exception('当前订单支付状态不是待付款');
            }

            $payInfo->status=Pay::STATUS_YIZHIFU;
            $payInfo->payment_time = time();
            if($paytype == 'wechat'){
                $payInfo->transaction_id = $data['transaction_id'];
            }elseif ($paytype == 'alipay'){
                $payInfo->transaction_id = $data['trade_no'];
            }
            $payInfo->save();

            //余额充值
            if ($payInfo->order_type == Pay::ORDER_TYPE_YUE) {
                UserRechargeOrder::paymentSuccess($payInfo->recharge_order_id);
            }
            //租赁订单押金支付
            elseif ($payInfo->order_type == Pay::ORDER_TYPE_YAJIN){
                \app\common\model\mycurrency\LeaseDeposit::paymentSuccess($payInfo->lease_deposit_id,$payInfo->pay_type);
            }
            //租赁订单租赁费用支付
            else if($payInfo->order_type == Pay::ORDER_TYPE_ZULINFEIYONG){
                LeaseOrderPay::paySuccess($payInfo->lease_order_pay_id,$payInfo->pay_type);
            }


            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            \think\Log::record("支付回调逻辑处理错误:" . $e->getMessage() . ' 订单号：' . $outTradeNo, "error");
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }

    }

    /**
     * 微信申请退款 回调
    */
    public function wechatRefundNotify() {
        $config = Config::get('wechatandalipay.wechat_miniapp');
        $xml = file_get_contents("php://input");
        //$xml = '<xml><return_code>SUCCESS</return_code><appid><![CDATA[wx1b4ad6704dace08e]]></appid><mch_id><![CDATA[1691127934]]></mch_id><nonce_str><![CDATA[b8be09b8aa0ecbcdd88d638bce6c3dfb]]></nonce_str><req_info><![CDATA[D0lbEPh8cusuKaE+A2cJ9z9h/E+pHapa0PY3/rmtieJTmUdmVAVeipcE6qHtsQkmZFXQUXrohUtnPJkQAaeXJ+rl1KC3wXagpbhpeL/8eDVB7bYyFP/wTUsqbd1CJ/KZZgZ662AhaLnY94V69VGZwszZsrUgD1c8wpfskmubYL46vC7dQ15ZqI+TTQsTKQrcgJnIv2YqQVfPcHYSWygdo8xNXpsyDhRzZ5wxOT+uN4X4RgNJtgduSzH21GjA5UaRXkHAjYd37zwznW0+Pe2ezkEweXAAmyRr77SupPIxwUftAhPxLP6Mcg4nMufvI+kym/8SJ2TsL9DIfDwlzMCQNEqw8T0ib4ysuctri3TyKBU1Mv00rBEXW2T3Wl67n0OUH5Njj6sBEJBlj8Yi765dzCg/4MnHSJtDJvDfjUcUFjleOGm+GzQ4opiMJ187ZFHN4DxOG2B6bXfTHo46i+wDNxkBN2SeyW7rqsOIVeUzeq4S/z8C/KZe5NVp6wEbQ7ZmNEVcOUEyC06NHFcjv++AovY7rz2hKaCFL8ULKwxRg+vsS2+Q2m3TU9D3TQ0YUdwK760Von0Q+S+rkLJrwMSnmJKzZMfz2pzJcbn7jc/oUdPtFvmw4b0TYoKydXm468lIPKuwyO+dDP5iYhnDvxLzldLerqlYBwR3Ndtvgn2ukt3Z36IUk6oq8AikQPtgXIC7NT78WZK9Ug2fK8AjiJvc4sQM+w89pXyBhLZgWeeuhYIT5IGdwEJzRoF9WycUdIakotsQ6FsRgkzIyx0A0UsvI2EdNO1I0xibrVDXOEHKxwoFYb652Hw4ZLFiOGg2GE92TvcASFJevZhh22a4yfXRIP5qJZwEn3nKbW89tzBtgwI4AZrFwKGo5c+FCOZwZd1iCLCweyLx9oBi0zFH58U/1teiBxi9YVYx/B0nUiqPAz7RVXbFfXqiyi849DtfiC2desN7oU3dAlrC4y4da8VYTeX0X0LI+6sspL67fZJ4VFPX01IOKTVZ9hg8quf5Pok5MMp+I0OOAHPNca8ZRc6cPPr7m1B/kyoXKaZTkUD2pSVW+G6HJbYff8xInZznI47lb0Gl93H4fQT5oGoc6CZfv2PxW81yrUSFzb5grWC8ytmxla83eK2ytC44m+RcVKSM]]></req_info></xml>';
        //db('test')->insertGetId(array('texta'=>$xml));
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        $req_infoB = base64_decode($array_data['req_info'], true);//base64解密码
        $req_infoC = openssl_decrypt($req_infoB, 'aes-256-ecb', md5($config['wxkey_v2']), OPENSSL_RAW_DATA);//使用加密的md5进行aes-256-ecb解密，获得xml格式数据
        $req_infoD = xmlToArray($req_infoC);//xml转数组
        $pay = Pay::where(['ordersn' => $req_infoD['out_trade_no']])->find();
        if($pay){
            if ($array_data['return_code'] == 'SUCCESS') {
                if($req_infoD['refund_status'] == 'SUCCESS'){
                    $pay->refund_type = Pay::REFUND_TYPE_YITUIKUAN;
                    $pay->out_refund_no = $req_infoD['out_refund_no'];
                    $pay->refund_completed_time = time();
                    $pay->refund_id = $req_infoD['refund_id'];
                    $pay->save();
                    if ($pay->order_type == Pay::ORDER_TYPE_YAJIN){//租赁订单押金支付退款
                        //处理押金退款成功后逻辑
                        \app\common\model\mycurrency\LeaseDeposit::refundSuccess(
                            $pay->lease_deposit_id,
                            \app\common\model\mycurrency\LeaseDeposit::REFUND_TYPE_YUANLU
                        );
                    }
                }else{//退款失败
                    $pay->refund_type = Pay::REFUND_TYPE_WEITUIKUAN;
                    $pay->save();
                }
            }
        }
        exit(200);
    }






}
